package com.pv.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.pv.common.to.user.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.Map;

/**
 * @Description:
 * @Author: Zk
 * @Date: 2021/8/23 15:12
 */
public class UserUtil {

        /**
         * 获取登陆的 LoginAppUser
         *
         * @return
         */
        @SuppressWarnings("rawtypes")
        public static User getUser() {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication instanceof OAuth2Authentication) {
                OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication;
                authentication = oAuth2Auth.getUserAuthentication();

                if (authentication instanceof UsernamePasswordAuthenticationToken) {
                    UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
                    Object principal = authentication.getPrincipal();
                    if (principal instanceof User) {
                        return (User) principal;
                    }
                    Map map = (Map) authenticationToken.getDetails();
                    map = (Map) map.get("principal");

                    return JSONObject.parseObject(JSONObject.toJSONString(map), User.class);
                }
            }
            return null;
        }
}
